#!/usr/bin/env python

import os
import sys
import socket
import xmlrpclib

from hyperiontv.tpvrserver import TpvrServer
from hyperiontv.superdaemon import SuperDaemon

EXTHOST = ""
EXTPORT = 9999
LOCALPORT = 9998

if __name__ == "__main__":
    daemon = TpvrServer('/tmp/tpvr-server.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            try:
                xmlrpclib.ServerProxy("http://%s:%s" % ("localhost", LOCALPORT)).safeStop()
            except socket.error:
                print "Appears to already be stopped."
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            print "Directing process to safely stop.."
            xmlrpclib.ServerProxy("http://%s:%s" % ("localhost", LOCALPORT)).safeStop()
            print "Restarting daemon.."
            daemon.restart()
            print "Done."
        elif 'forcestop' == sys.argv[1]:
            daemon.stop()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart|forcestop" % sys.argv[0]
        sys.exit(2)
